package com.stfalcon.chatkit.sample.features.demo.custom.holder;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.stfalcon.chatkit.messages.MessageHolders;
import com.stfalcon.chatkit.messages.MessageInput;
import com.stfalcon.chatkit.messages.MessagesList;
import com.stfalcon.chatkit.messages.MessagesListAdapter;
import com.stfalcon.chatkit.sample.R;
import com.stfalcon.chatkit.sample.common.data.fixtures.MessagesFixtures;
import com.stfalcon.chatkit.sample.common.data.model.Message;
import com.stfalcon.chatkit.sample.features.demo.DemoMessagesActivity;
import com.stfalcon.chatkit.sample.features.demo.custom.holder.holders.messages.CustomIncomingImageMessageViewHolder;
import com.stfalcon.chatkit.sample.features.demo.custom.holder.holders.messages.CustomIncomingTextMessageViewHolder;
import com.stfalcon.chatkit.sample.features.demo.custom.holder.holders.messages.CustomOutcomingImageMessageViewHolder;
import com.stfalcon.chatkit.sample.features.demo.custom.holder.holders.messages.CustomOutcomingTextMessageViewHolder;
import com.stfalcon.chatkit.sample.url.URLConstant;
import com.stfalcon.chatkit.sample.utils.AppUtils;
import com.stfalcon.chatkit.sample.utils.CipherHelper;
import com.stfalcon.chatkit.sample.utils.SM2KeyPair;
import com.stfalcon.chatkit.sample.utils.SM2Util;
import com.stfalcon.chatkit.sample.utils.SharedPreferencesAtrribute;
import com.stfalcon.chatkit.sample.websocket.WebsocketManager;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

public class CustomHolderMessagesActivity extends DemoMessagesActivity
        implements MessagesListAdapter.OnMessageLongClickListener<Message>,
        MessageInput.InputListener,
        MessageInput.AttachmentsListener {

    SharedPreferences sharedPreferences;

    public static void open(Context context) {
        context.startActivity(new Intent(context, CustomHolderMessagesActivity.class));
    }

    WebsocketManager wsManager;
    private MessagesList messagesList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_holder_messages);

        this.sharedPreferences = this.getSharedPreferences(SharedPreferencesAtrribute.SAVE_FILE_NAME, SharedPreferencesAtrribute.FILE_MODE);

        messagesList = findViewById(R.id.messagesList);
        initAdapter();


        MessageInput input = findViewById(R.id.input);
        input.setInputListener(this);
        input.setAttachmentsListener(this);

        wsManager = new WebsocketManager.Builder(getBaseContext()).client(
                new OkHttpClient().newBuilder()
                        .pingInterval(15, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(true)
                        .build())
                .needReconnect(true)
                .wsUrl(URLConstant.WEB_SOCKET_URL)
                .build(SharedPreferencesAtrribute.getSharedPreferences().getString("token", ""), messagesAdapter);

        new Thread(() -> {
            wsManager.startConnect();
        }).run();


    }

    @Override
    public boolean onSubmit(CharSequence input) {

        String strData = input.toString();

        new Thread(() -> {

            String  token = this.sharedPreferences.getString("token", "");


                try {

                    long time = System.currentTimeMillis();
// sm4
                    System.out.println("开始****************************"+ time);
                    String json = strData;
                    System.out.println("加密前："+json);
                    //自定义的32位16进制秘钥86C63180C2806ED1F47B859DE501215B

                   ;

                    String key =  wsManager.getSecretKey();
                    Log.i("密钥为key", key);
                    if (key.equals("") || key.length() == 0) {
                        Log.i("密钥为空", "");

                        return;
                    }
                    String cipher = CipherHelper.encryptEcb(key,json);//sm4加密
                    Log.i("加密后：", cipher + ",sm4共计：" + (System.currentTimeMillis() - time));
                   // Log.i("校验：", CipherHelper.verifyEcb(key,cipher,json));//校验加密前后是否为同一数据

                    Map<String, Object> message = new HashMap<String, Object>();

                    Map<String, Object> ext = new HashMap<String, Object>();

                    ext.put("msg", cipher);
                    ext.put("token", token);
                    ext.put("sender", this.getIntent().getStringExtra("userId"));

                    message.put("cmd", "server.sendMessage");

                    Log.i("userToken", this.getIntent().getStringExtra("userId"));

                    Log.i("sender", this.getIntent().getStringExtra("userId"));

                    message.put("data", ext);

                    message.put("ext", "{}");

                    Log.i("message:", message.toString());

                    Gson son = new Gson();

                    wsManager.sendMessage(son.toJson(message));

                    long timeSM2 = System.currentTimeMillis();


                    SM2Util sm2 = new SM2Util();
                    SM2KeyPair keyPair = sm2.generateKeyPair();
                    byte[] data = sm2.encrypt(strData,keyPair.getPublicKey());

                    Log.i("sm2共计：", "" + (System.currentTimeMillis() - timeSM2));

                    sm2.decrypt(data, keyPair.getPrivateKey());


                    System.out.println("data is:"+ Arrays.toString(data));
                }catch (Exception e) {
                    System.out.println(e.getMessage());
                }




        }).run();

        messagesAdapter.addToStart(
                MessagesFixtures.getTextMessage(strData), true);
        return true;
    }

    @Override
    public void onAddAttachments() {
        messagesAdapter.addToStart(MessagesFixtures.getImageMessage(), true);
    }

    @Override
    public void onMessageLongClick(Message message) {
        AppUtils.showToast(this, R.string.on_log_click_message, false);
    }

    private void initAdapter() {

        //We can pass any data to ViewHolder with payload
        CustomIncomingTextMessageViewHolder.Payload payload = new CustomIncomingTextMessageViewHolder.Payload();
        //For example click listener
        payload.avatarClickListener = () -> Toast.makeText(CustomHolderMessagesActivity.this,
                "Text message avatar clicked", Toast.LENGTH_SHORT).show();

        MessageHolders holdersConfig = new MessageHolders()
                .setIncomingTextConfig(
                        CustomIncomingTextMessageViewHolder.class,
                        R.layout.item_custom_incoming_text_message,
                        payload)
                .setOutcomingTextConfig(
                        CustomOutcomingTextMessageViewHolder.class,
                        R.layout.item_custom_outcoming_text_message)
                .setIncomingImageConfig(
                        CustomIncomingImageMessageViewHolder.class,
                        R.layout.item_custom_incoming_image_message)
                .setOutcomingImageConfig(
                        CustomOutcomingImageMessageViewHolder.class,
                        R.layout.item_custom_outcoming_image_message);

        super.messagesAdapter = new MessagesListAdapter<>(super.senderId, holdersConfig, super.imageLoader);
        super.messagesAdapter.setOnMessageLongClickListener(this);
        super.messagesAdapter.setLoadMoreListener(this);
        messagesList.setAdapter(super.messagesAdapter);
    }
}
